package com.test.java.watermark;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Slf4j
public class AddWatermarkUtils {

    // 水印字体
    private static final Font FONT = new Font("微软雅黑", Font.PLAIN, 24);

    // 透明度
    private static final AlphaComposite COMPOSITE = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);

    // 水印之间的间隔
    private static final int X_MOVE = 150;

    // 水印之间的间隔
    private static final int Y_MOVE = 200;

    public static long addTextWaterMark(String inputImgPath, Font font, Color markContentColor,
                                       String waterMarkContent,
                                       String outImgPath) throws IOException {

        // 读取原图片信息
        File srcFile = new File(inputImgPath);
        File outFile = new File(outImgPath);
        long start = System.currentTimeMillis();
        BufferedImage srcImg = ImageIO.read(srcFile);

        // 图片宽、高
        int imgWidth = srcImg.getWidth();
        int imgHeight = srcImg.getHeight();

        // 图片缓存
        BufferedImage bufImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

        // 创建绘图工具
        Graphics2D graphics = bufImg.createGraphics();

        // 画入原始图像
        graphics.drawImage(srcImg, 0, 0, imgWidth, imgHeight, null);

        // 设置水印颜色
        graphics.setColor(markContentColor);

        // 设置水印透明度
        graphics.setComposite(COMPOSITE);

        // 设置倾斜角度
        graphics.rotate(Math.toRadians(-35), (double) bufImg.getWidth() / 2,
                (double) bufImg.getHeight() / 2);

        // 设置水印字体
        graphics.setFont(font);

        // 消除java.awt.Font字体的锯齿
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int xCoordinate = -imgWidth / 2, yCoordinate;
        // 字体长度
        int markWidth = FONT.getSize() * getTextLength(waterMarkContent);
        // 字体高度
        int markHeight = FONT.getSize();

        graphics.drawString(waterMarkContent, -200, -200);

        // 循环添加水印
//        while (xCoordinate < imgWidth * 1.5) {
//            yCoordinate = -imgHeight / 2;
//            while (yCoordinate < imgHeight * 1.5) {
//                graphics.drawString(waterMarkContent, xCoordinate, yCoordinate);
//                yCoordinate += markHeight + Y_MOVE;
//            }
//            xCoordinate += markWidth + X_MOVE;
//        }

        // 释放画图工具
        graphics.dispose();
        long cost = System.currentTimeMillis() - start;
        System.out.println();
        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            // 输出图片
            ImageIO.write(bufImg, "jpg", fos);
            fos.flush();
        }
        return cost;
    }


    /**
     * 计算水印文本长度
     * 中文长度即文本长度
     * 英文长度为文本长度二分之一
     */
    public static int getTextLength(String text) {
        //水印文字长度
        int length = text.length();

        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }


    /**
     * 在图片右下角添加图片水印
     * @param srcImgFile    :源图片
     * @param targetImgPath :保存图片路径
     * @param watermarkFile  :水印文件
     * @throws Exception
     */
    public static void addImageWaterMark(File srcImgFile, String targetImgPath, File watermarkFile) throws Exception {
        try (FileOutputStream outImgStream = new FileOutputStream(targetImgPath);){
            Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            // 创建画笔
            Graphics2D graphics = bufImg.createGraphics();
            graphics.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);

            Image watermarkImage = ImageIO.read(watermarkFile);
            ImageIcon imageIcon = new ImageIcon(watermarkImage);
            Image watermarkIconImage = imageIcon.getImage();
            // 设置透明度
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));

            int width = watermarkImage.getWidth(null);
            int height = watermarkIconImage.getHeight(null);
            // 位置放右下角
            int x = srcImgWidth - width -5;
            int y = srcImgHeight - height - 5;
            // 写水印
            graphics.drawImage(watermarkIconImage, x, y, null);
            // 释放画笔
            graphics.dispose();
            // 输出图片
            ImageIO.write(bufImg, "jpg", outImgStream);
            outImgStream.flush();
        } catch (Exception e) {
            log.error("add watermark error file:{}, error:{}", srcImgFile.getName(), e);
        }
    }

    public static void main(String[] args) throws Exception {
        long total = 0;
//        for (int i = 0; i < 1; i++) {
//            total += addTextWaterMark("/Users/tongrui/develop/tempfiles/IMG_1193.JPG", FONT, Color.BLACK,
//                    "四季为农", "/Users/tongrui/develop/tempfiles/watermark/watermark_"+ i +".jpg");
//        }
        System.out.println(total * 1.0F / 100);
        addImageWaterMark(new File("/Users/tongrui/Downloads/2.jpg"),
                "/Users/tongrui/develop/tempfiles/watermark/watermark_22.jpeg",
                new File("/Users/tongrui/develop/tempfiles/四季为农水印3.png"));

    }
}

